/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package lib.plan;

import lib.exceptions.XMLParsingException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.List;
import java.util.ArrayList;
import lib.xml.ProductionPlanReader;
import lib.xml.XMLizable;
import org.xml.sax.SAXException;

/**
 * This class represents the production plan of the factory, it has a name for
 * difference it from the other production plans, the date of the last time it
 * was saved, and a collection of orders with different properties.
 * @see Order
 * @author Jorge Mira Yagüe
 */
public class ProductionPlan implements XMLizable {

    private String name;
    private Calendar whenModified;
    private List<Order> orders;

    /**
     * Builds a production plan with the given id
     * @param id the id of the preduction plan
     */
    public ProductionPlan(String id) {
        name = id;
        orders = new ArrayList<Order>();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Order> getOrders() {
        return orders;
    }

    public Calendar getWhenModified() {
        return whenModified;
    }

    public void setWhenModified(Calendar whenModified) {
        this.whenModified = whenModified;
    }

    public Order getOrder(int index) {
        return orders.get(index);
    }

    public void addOrder(Order order) {
        order.setNumber(orders.size());
        orders.add(order);
    }

    public Item getItem(int orderNumber, int itemNumber) {
        return orders.get(orderNumber).getItem(itemNumber);
    }

    /**
     * Saves the production plan using the production plan id for the file
     * name, appending it the date and the .cfg extension
     * @throws java.io.FileNotFoundException if can't create the file
     * @throws IOException when an error ocurred during I/O
     */
    public void Save() throws FileNotFoundException, IOException {
        SaveAs(new File(name + ".xml"));
    }

    /**
     * Saves the production plan using the specified value for the file name,
     * appending it the date and the .cfg extension
     * @param file the name for the file to save the production plan
     * @throws java.io.FileNotFoundException if can't create the file
     * @throws IOException when an error ocurred during I/O
     */
    public void SaveAs(File file) throws FileNotFoundException, IOException {
        if (!file.getName().endsWith(".xml")) {
            file = new File(file.getPath() + ".xml");
        }

        if (file.exists()) {
            Date date = new Date(file.lastModified());
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmm");
            String fileName = file.getPath();
            String backupName = file.getPath().substring(0, file.getPath().length() - 4) +
                    "-v" + format.format(date) + ".xml";
            file.renameTo(new File(backupName));
            file = new File(fileName);
        }
        whenModified = Calendar.getInstance();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(toXML().getBytes());
        fos.close();
    }

    /**
     * Loads a production plan into the object from the file specified
     * @param file the file with the production plan
     * @throws java.io.FileNotFoundException if the file doesn't exists
     * @throws XMLParsingException if occurs an error parsing the XML file
     */
    public static ProductionPlan Load(File file) throws FileNotFoundException,
            XMLParsingException,
            IOException {
        try {
            ProductionPlanReader ppr = new ProductionPlanReader();
            return ppr.getPPFromXML(file);
        } catch (SAXException saxe) {
            throw new XMLParsingException(file.getName());
        }
    }

    public String toXML() {
        if (whenModified == null) {
            whenModified = Calendar.getInstance();
        }
        String result = "<ProductionPlan ";
        result += "name=\"" + name + "\" ";
        result += "whenModified=\"" + whenModified.getTimeInMillis() + "\" ";
        result += ">\n";
        for (Order order : orders) {
            result += order.toXML();
        }
        result += "</ProductionPlan>\n";
        return result;
    }
}
